import store from "@/store"
import { constantRoutes, asyncRoutes } from "@/router"
// import { defineStore } from "pinia"

import { login as loginApi, getInfo as getInfoApi } from "@/api/admin/user"
import storage from '@/utils/storage'

export const usePermissionStore = defineStore("permission", () => {
 
  const token = ref({})
  const login = (data) => {
    return new Promise(function (resolve, reject) {
      loginApi(data).then(res => {
        if (res.success) {
          token.value = res.result
          
          storage.set('accessToken',res.result.accessToken)
          storage.set('refreshToken',res.result.refreshToken)
          storage.set('tokenType',res.result.tokenType)
          resolve(res)
        }
        else {
          reject(res)
        }

      })
        .catch(ex => {
          reject(ex)
        })
    })
  }

  const logout = () => {
    storage.clear()
    token.value = "";
    user.value = {}
    roles.value = []
    permissions.value = []
  }


  const user = ref({})
  const roles = ref([])
  const permissions = ref([])
  const getInfo = () => {
    return new Promise(function (resolve, reject) {
      getInfoApi().then(res => {
        if (res.success) {
          
          user.value = res.result.user
          roles.value = res.result.roles
          permissions.value = res.result.permissions

          resolve(res)
        }
        else {
          reject(res)
        }
      }) .catch(ex => {
        reject(ex)
      })

    })
  }


  const routes = ref([])
  const dynamicRoutes = ref([])

  const setRoutes = () => {
    //debugger
    const newRoutes= []
    for(const currentRoute of asyncRoutes) {
      if(currentRoute.meta.code) {
        const permission = permissions.value.find(t=>t.id == currentRoute.meta.code)
        if(permission == null) {
          continue
        }

        currentRoute.children = currentRoute.children.filter(t=>t.meta.code && permissions.value.find(x=>x.id == t.meta.code) )

        newRoutes.push(currentRoute)
      }
    }

    routes.value = constantRoutes.concat(asyncRoutes)
    dynamicRoutes.value = newRoutes
  }

  return {
    routes, dynamicRoutes, setRoutes,
    token, login, logout,
    user, roles, permissions, getInfo
  }
})




/** 在 setup 外使用 */
export function usePermissionStoreHook() {
  return usePermissionStore(store)
}
